using Domain;
using ErrorCode;
using Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using RabbitTraceability.Api.Applications.Command;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace RabbitTraceability.Api.Applications.CommandHandler
{
    /// <summary>
    /// 修改溯源信息的命令处理器
    /// </summary>
    public class UpdateTraceabilityInfoCommandHandler : IRequestHandler<UpdateTraceabilityInfoCommand, bool>
    {
        private readonly IRepository<TraceabilityInfo> _repository;
        private readonly ILogger<UpdateTraceabilityInfoCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repository">溯源信息仓储</param>
        /// <param name="logger">日志记录器</param>
        public UpdateTraceabilityInfoCommandHandler(
            IRepository<TraceabilityInfo> repository,
            ILogger<UpdateTraceabilityInfoCommandHandler> logger)
        {
            _repository = repository;
            _logger = logger;
        }

        /// <summary>
        /// 处理修改溯源信息的命令
        /// </summary>
        /// <param name="request">请求命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>是否修改成功</returns>
        public async Task<bool> Handle(UpdateTraceabilityInfoCommand request, CancellationToken cancellationToken)
        {
            _logger.LogInformation("修改溯源信息，溯源编号：{TraceabilityId}", request.TraceabilityId);

            // 参数验证
            if (string.IsNullOrWhiteSpace(request.TraceabilityId))
            {
                _logger.LogWarning("溯源编号不能为空");
                throw new ApiException(ResultCode.参数错误, "溯源编号不能为空");
            }

            // 查询溯源信息
            var traceabilityInfo = await _repository.GetAll()
                .FirstOrDefaultAsync(t => t.TraceabilityId == request.TraceabilityId, cancellationToken);

            if (traceabilityInfo == null)
            {
                _logger.LogWarning("未找到溯源信息，溯源编号：{TraceabilityId}", request.TraceabilityId);
                throw new ApiException(ResultCode.数据不存在, $"未找到溯源编号为 {request.TraceabilityId} 的溯源信息");
            }

            try
            {
                // 更新溯源信息
                traceabilityInfo.ProductName = request.ProductName;
                traceabilityInfo.ProductionBatch = request.ProductionBatch;
                traceabilityInfo.ShelfLife = request.ShelfLife;
                traceabilityInfo.ProductionLicense = request.ProductionLicense;
                traceabilityInfo.Manufacturer = request.Manufacturer;
                traceabilityInfo.CoverImage = request.CoverImage;

                // 保存更改
                await _repository.UpdateAsync(traceabilityInfo);
                _logger.LogInformation("修改溯源信息成功，溯源编号：{TraceabilityId}", request.TraceabilityId);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改溯源信息失败，溯源编号：{TraceabilityId}", request.TraceabilityId);
                throw new ApiException(ResultCode.服务器错误, "修改溯源信息失败，请稍后再试");
            }
        }
    }
} 